package com.cyl.manager.aws.service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.aws.domain.entity.ShopStatistics;
import com.cyl.manager.aws.mapper.ShopStatisticsMapper;
import com.cyl.manager.aws.pojo.query.ShopStatisticsQuery;
import com.cyl.manager.aws.pojo.vo.ShopStatisticsSqlVO;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.ruoyi.common.annotation.Excel;

import cn.hutool.core.date.DateUtil;

/**
 * 店铺数据统计Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class ShopStatisticsService {
    @Autowired
    private ShopStatisticsMapper shopStatisticsMapper;

    @Autowired
    private MemberMapper memberMapper;
    
    /**
     * 查询店铺数据统计
     *
     * @param id 店铺数据统计主键
     * @return 店铺数据统计
     */
    public ShopStatistics selectById(Long id) {
        return shopStatisticsMapper.selectById(id);
    }
    
    /**
     * 获取最新更新时间
     * @param query
     * @param page
     * @return
     */
    public LocalDateTime selectMaxCreateTime2() {
    	LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(5L);
        QueryWrapper<ShopStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.select( "max(create_time) create_time");
        ShopStatistics shopStatistics = shopStatisticsMapper.selectOne(queryWrapper);
        if(shopStatistics!=null) {
        	localDateTime =  shopStatistics.getCreateTime();
        }
        return localDateTime;

    }
    
    
    /**
     * 获取最新更新时间
     * @param query
     * @param page
     * @return
     */
    public String selectMaxCreateTime() {
    	LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(5L);
        QueryWrapper<ShopStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.select( "max(create_time) create_time");
        ShopStatistics shopStatistics = shopStatisticsMapper.selectOne(queryWrapper);
        if(shopStatistics!=null) {
        	localDateTime =  shopStatistics.getCreateTime();
        }
        return DateUtil.formatLocalDateTime(localDateTime);

    }
 
    /**
     * 查询店铺数据统计列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 店铺数据统计
     */
    public List<ShopStatistics> selectList(ShopStatisticsQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
       // QueryWrapper<ShopStatistics> qw = new QueryWrapper<>();
       MPJQueryWrapper<ShopStatistics> qw = new MPJQueryWrapper<>();

        String hbx = query.getHbx();//合并项1日期2店铺
        if(hbx!=null) {
        	if("1".equals(hbx)) {
        		query.setSfDate("false");
        		query.setType("3");
        		query.setByColumn(null);
        	}
        	if("2".equals(hbx)) {
        		query.setSfDate("true");
        		query.setType("0");
        	}
        }
       
        String type = query.getType();
        
        
       
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        
   
        
        String date = "t.tjdata , ";
        String sfDate =  query.getSfDate();
        if(sfDate!=null && "false".equals(sfDate)) {
        	date = "";
        }
        String selectGroupBy = null;
        if("0".equals(type)) {
        	selectGroupBy = ("t.tjdata");
        }
        if("1".equals(type)) {// 1
        	selectGroupBy = (date + " t.dept_zbj_id ");
        }
        if("2".equals(type)) {
        	selectGroupBy = (date +  " t.dept_zbj_id ,t.dept_tz_id ");
        }
        if("3".equals(type)) {
        	selectGroupBy = (date +  " t.dept_zbj_id , t.dept_tz_id , t.dept_dp_id ");
        }
     
        
        if(selectGroupBy!=null) {
            qw.select(selectGroupBy + "	,\r\n" + 
     		   		"					max(IFNULL(t.member_conut, 0)) member_conut,\r\n" + 
     		   		"					sum(IFNULL(t.member_day_conut, 0)) member_day_conut,\r\n" + 
     		   		"					sum(IFNULL(t.member_login_conut, 0)) member_login_conut,\r\n" + 
     		   		"					sum(IFNULL(t.pay_quantity, 0)) pay_quantity , \r\n" + 
     		   		"					sum(IFNULL(t.pay_amount, 0)) pay_amount , \r\n" + 
     		   		"					sum(IFNULL(t.pay_fee_amount, 0)) pay_fee_amount , \r\n" + 
     		   		"					sum(IFNULL(t.pay_conut, 0)) pay_conut, \r\n" + 
     		   		"					sum(IFNULL(t.ret_quantity, 0))  ret_quantity, \r\n" + 
     		   		"					sum(IFNULL(t.ret_amount, 0)) ret_amount, \r\n" + 
     		   		"					sum(IFNULL(t.ret_fee_amount, 0)) ret_fee_amount , \r\n" + 
     		   		"					sum(IFNULL(t.ret_conut, 0)) ret_conut");
            qw.groupBy(selectGroupBy);
        }else {
        	 qw.select("t.*"); 
        }
        Long qxDeptId = query.getQxDeptId();
        if(qxDeptId!=null) {
        	qw.join(" ", true, " JOIN (SELECT dept_dp_id AS dept_dp_id FROM sys_dept_dept  WHERE  dept_id =  "+qxDeptId+") AS sys_dd\r\n" + 
        			"            			ON t.dept_dp_id = sys_dd.dept_dp_id  ");
        } 
        
        Integer[] tjdataRange = query.getTjdataRange();
        if (tjdataRange != null && tjdataRange.length == 2) {
            Integer start = tjdataRange[0];
            if (start != null) {
                qw.ge("t.tjdata", start);
            }
            Integer end = tjdataRange[1];
            if (end != null) {
                qw.le("t.tjdata", end);
            }
        }
        Long deptZbjId = query.getDeptZbjId();
        if (deptZbjId != null) {
            qw.eq("t.dept_zbj_id", deptZbjId);
        }
        
        Long deptTzId = query.getDeptTzId();
        if (deptTzId != null) {
            qw.eq("t.dept_tz_id", deptTzId);
        }
        
        Long deptDpId = query.getDeptDpId();
        if (deptDpId != null) {
        	qw.eq("t.dept_dp_id", deptDpId);
        }else {
        	 ArrayList<Long> deptDpIds= query.getDeptDpIds();
             if(deptDpIds!=null && deptDpIds.size()>0) {
             	if(deptDpIds.size()==1) {
             		qw.eq("t.dept_dp_id", deptDpIds.get(0));
             	}else {
                     qw.in("t.dept_dp_id", deptDpIds);
             	}
             }
        }
       
        Integer tjyear = query.getTjyear();
        if (tjyear != null) {
            qw.eq("t.tjyear", tjyear);
        }
        Integer tjmonth = query.getTjmonth();
        if (tjmonth != null) {
            qw.eq("t.tjmonth", tjmonth);
        }
        Integer tjweek = query.getTjweek();
        if (tjweek != null) {
            qw.eq("t.tjweek", tjweek);
        }
        Integer tjday = query.getTjday();
        if (tjday != null) {
            qw.eq("t.tjday", tjday);
        }
        Integer[] memberConutRange = query.getMemberConutRange();
        if (memberConutRange != null && memberConutRange.length == 2) {
            Integer start = memberConutRange[0];
            if (start != null) {
                qw.ge("t.member_conut", start);
            }
            Integer end = memberConutRange[1];
            if (end != null) {
                qw.le("t.member_conut", end);
            }
        }
        Integer[] memberDayConutRange = query.getMemberDayConutRange();
        if (memberDayConutRange != null && memberDayConutRange.length == 2) {
            Integer start = memberDayConutRange[0];
            if (start != null) {
                qw.ge("t.member_day_conut", start);
            }
            Integer end = memberDayConutRange[1];
            if (end != null) {
                qw.le("t.member_day_conut", end);
            }
        }
        
        Integer[] memberLoginConutRange = query.getMemberLoginConutRange();
        if (memberLoginConutRange != null && memberLoginConutRange.length == 2) {
            Integer start = memberLoginConutRange[0];
            if (start != null) {
                qw.ge("t.member_login_conut", start);
            }
            Integer end = memberLoginConutRange[1];
            if (end != null) {
                qw.le("t.member_login_conut", end);
            }
        }
        
        
        Integer[] payQuantityRange = query.getPayQuantityRange();
        if (payQuantityRange != null && payQuantityRange.length == 2) {
            Integer start = payQuantityRange[0];
            if (start != null) {
                qw.ge("t.pay_quantity", start);
            }
            Integer end = payQuantityRange[1];
            if (end != null) {
                qw.le("t.pay_quantity", end);
            }
        }
        BigDecimal[] payAmountRange = query.getPayAmountRange();
        if (payAmountRange != null && payAmountRange.length == 2) {
            BigDecimal start = payAmountRange[0];
            if (start != null) {
                qw.ge("t.pay_amount", start);
            }
            BigDecimal end = payAmountRange[1];
            if (end != null) {
                qw.le("t.pay_amount", end);
            }
        }
        BigDecimal[] payFeeAmountRange = query.getPayFeeAmountRange();
        if (payFeeAmountRange != null && payFeeAmountRange.length == 2) {
            BigDecimal start = payFeeAmountRange[0];
            if (start != null) {
                qw.ge("t.pay_fee_amount", start);
            }
            BigDecimal end = payFeeAmountRange[1];
            if (end != null) {
                qw.le("t.pay_fee_amount", end);
            }
        }
        Integer[] payConutRange = query.getPayConutRange();
        if (payConutRange != null && payConutRange.length == 2) {
            Integer start = payConutRange[0];
            if (start != null) {
                qw.ge("t.pay_conut", start);
            }
            Integer end = payConutRange[1];
            if (end != null) {
                qw.le("t.pay_conut", end);
            }
        }
        Integer[] retQuantityRange = query.getRetQuantityRange();
        if (retQuantityRange != null && retQuantityRange.length == 2) {
            Integer start = retQuantityRange[0];
            if (start != null) {
                qw.ge("t.ret_quantity", start);
            }
            Integer end = retQuantityRange[1];
            if (end != null) {
                qw.le("t.ret_quantity", end);
            }
        }
        BigDecimal[] retAmountRange = query.getRetAmountRange();
        if (retAmountRange != null && retAmountRange.length == 2) {
            BigDecimal start = retAmountRange[0];
            if (start != null) {
                qw.ge("t.ret_amount", start);
            }
            BigDecimal end = retAmountRange[1];
            if (end != null) {
                qw.le("t.ret_amount", end);
            }
        }
        BigDecimal[] retFeeAmountRange = query.getRetFeeAmountRange();
        if (retFeeAmountRange != null && retFeeAmountRange.length == 2) {
            BigDecimal start = retFeeAmountRange[0];
            if (start != null) {
                qw.ge("t.ret_fee_amount", start);
            }
            BigDecimal end = retFeeAmountRange[1];
            if (end != null) {
                qw.le("t.ret_fee_amount", end);
            }
        }
        Integer[] retConutRange = query.getRetConutRange();
        if (retConutRange != null && retConutRange.length == 2) {
            Integer start = retConutRange[0];
            if (start != null) {
                qw.ge("t.ret_conut", start);
            }
            Integer end = retConutRange[1];
            if (end != null) {
                qw.le("t.ret_conut", end);
            }
        }
        String byDesc  = query.getByDesc();
    	String byColumn  = query.getByColumn();
    	if(byColumn!=null && !byColumn.equals("")) {
    		if(!byColumn.startsWith("t.")) {
    			byColumn = "t."+byColumn;
    		}
    		if("true".equals(byDesc)) {
            	qw.orderByDesc(byColumn);
            }else {
            	qw.orderByAsc(byColumn);
            }
    	}
        return shopStatisticsMapper.selectList(qw);
    }
  
    /**
     * 新增店铺数据统计
     *
     * @param shopStatistics 店铺数据统计
     * @return 结果
     */
    public int insert(ShopStatistics shopStatistics) {
    	return 0;
//        shopStatistics.setCreateTime(LocalDateTime.now());
//        return shopStatisticsMapper.insert(shopStatistics);
    }

    /**
     * 修改店铺数据统计
     *
     * @param shopStatistics 店铺数据统计
     * @return 结果
     */
    public int update(ShopStatistics shopStatistics) {
    	return 0;

//        return shopStatisticsMapper.updateById(shopStatistics);
    }

    /**
     * 批量删除店铺数据统计
     *
     * @param ids 需要删除的店铺数据统计主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
    	return 0;

//        return shopStatisticsMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除店铺数据统计信息
     *
     * @param id 店铺数据统计主键
     * @return 结果
     */
    public int deleteById(Long id) {
    	return 0;

//        Long[] ids = {id};
//        return shopStatisticsMapper.updateDelFlagByIds(ids);
    }
    
    
    /**
     * 批量删除店铺数据统计
     *
     * @param ids 需要删除的店铺数据统计主键
     * @return 结果
     */
    @Transactional
    public  int insertShopDay(LocalDateTime strTime,LocalDateTime endTime) {
       	int tjdata = Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd"));
 		int	tjyear = Integer.parseInt(DateUtil.format(strTime, "yyyy"));
 		int	tjmonth = Integer.parseInt(DateUtil.format(strTime, "MM"));
 		int	tjweek = Integer.parseInt(DateUtil.format(strTime, "w"));
 		int	tjday = Integer.parseInt(DateUtil.format(strTime, "dd"));
 		ShopStatisticsSqlVO shopStatisticsSqlVO = new ShopStatisticsSqlVO();
    	shopStatisticsSqlVO.setCreateTime(LocalDateTime.now());
    	shopStatisticsSqlVO.setStrTime(strTime);
    	shopStatisticsSqlVO.setEndTime(endTime);
    	shopStatisticsSqlVO.setTjdata(tjdata);
    	shopStatisticsSqlVO.setTjyear(tjyear);
    	shopStatisticsSqlVO.setTjmonth(tjmonth);
    	shopStatisticsSqlVO.setTjweek(tjweek);
    	shopStatisticsSqlVO.setTjday(tjday);
 		
    	QueryWrapper<ShopStatistics> wrapper = new QueryWrapper<ShopStatistics>();
    	wrapper.eq("tjdata", shopStatisticsSqlVO.getTjdata());
    	shopStatisticsMapper.delete(wrapper);
        return shopStatisticsMapper.insertShopDay(shopStatisticsSqlVO);
    }
    
    /**
     * 批量删除店铺数据统计
     *
     * @param ids 需要删除的店铺数据统计主键
     * @return 结果
     */
    public  ShopStatistics selectShopToDayByDeptDpId(Long deptDpId) {
    	if(deptDpId == null) {
  		  return null;
  	    }
    	ShopStatistics shopStatistics = null;
        LocalDate thisDate = LocalDate.now();
    	LocalDateTime strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
  	 	LocalDateTime endTime  = LocalDateTime.of(thisDate, LocalTime.MAX);
       	int tjdata = Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd"));
 		int	tjyear = Integer.parseInt(DateUtil.format(strTime, "yyyy"));
 		int	tjmonth = Integer.parseInt(DateUtil.format(strTime, "MM"));
 		int	tjweek = Integer.parseInt(DateUtil.format(strTime, "w"));
 		int	tjday = Integer.parseInt(DateUtil.format(strTime, "dd"));
 		ShopStatisticsSqlVO shopStatisticsSqlVO = new ShopStatisticsSqlVO();
    	shopStatisticsSqlVO.setCreateTime(LocalDateTime.now());
    	shopStatisticsSqlVO.setStrTime(strTime);
    	shopStatisticsSqlVO.setEndTime(endTime);
    	shopStatisticsSqlVO.setTjdata(tjdata);
    	shopStatisticsSqlVO.setTjyear(tjyear);
    	shopStatisticsSqlVO.setTjmonth(tjmonth);
    	shopStatisticsSqlVO.setTjweek(tjweek);
    	shopStatisticsSqlVO.setTjday(tjday);
    	shopStatisticsSqlVO.setDeptDpId(deptDpId);
    	shopStatisticsSqlVO.setGroupByType(3);
    	shopStatisticsSqlVO.setGroupBy(" dept_zbj_id , dept_tz_id , dept_dp_id ");
    	shopStatisticsSqlVO.setGroupByzd(" dept_zbj_id , dept_tz_id , dept_dp_id, ");
    	 
    	List<ShopStatistics> list =	shopStatisticsMapper.selectShopToDay(shopStatisticsSqlVO);
    	if(list!=null && list.size()>0) {
    		shopStatistics = list.get(0);
    		QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
			queryWrapper.between("spread_time", strTime, endTime);
			queryWrapper.eq("dept_dp_id", deptDpId);
			shopStatistics.setMemberDayConut(memberMapper.selectCount(queryWrapper));
    		return shopStatistics;
    	}
        return null;
    }
    
    
    /**
     * 批量删除店铺数据统计
     *
     * @param ids 需要删除的店铺数据统计主键
     * @return 结果
     */
    public  ShopStatistics selectShopToDayByDeptDpId3(Long deptDpId,Long spreaduid,LocalDateTime strTime,LocalDateTime endTime) {
    	if(deptDpId == null) {
  		  return null;
  	    }
    	ShopStatistics shopStatistics = null;
       	int tjdata = Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd"));
 		int	tjyear = Integer.parseInt(DateUtil.format(strTime, "yyyy"));
 		int	tjmonth = Integer.parseInt(DateUtil.format(strTime, "MM"));
 		int	tjweek = Integer.parseInt(DateUtil.format(strTime, "w"));
 		int	tjday = Integer.parseInt(DateUtil.format(strTime, "dd"));
 		ShopStatisticsSqlVO shopStatisticsSqlVO = new ShopStatisticsSqlVO();
    	shopStatisticsSqlVO.setCreateTime(LocalDateTime.now());
    	shopStatisticsSqlVO.setStrTime(strTime);
    	shopStatisticsSqlVO.setEndTime(endTime);
    	shopStatisticsSqlVO.setTjdata(tjdata);
    	shopStatisticsSqlVO.setTjyear(tjyear);
    	shopStatisticsSqlVO.setTjmonth(tjmonth);
    	shopStatisticsSqlVO.setTjweek(tjweek);
    	shopStatisticsSqlVO.setTjday(tjday);
    	shopStatisticsSqlVO.setDeptDpId(deptDpId);
    	shopStatisticsSqlVO.setSpreaduid(spreaduid);
    	shopStatisticsSqlVO.setGroupByType(3);
    	shopStatisticsSqlVO.setGroupBy(" dept_zbj_id , dept_tz_id , dept_dp_id ");
    	shopStatisticsSqlVO.setGroupByzd(" dept_zbj_id , dept_tz_id , dept_dp_id, ");
    	 
    	List<ShopStatistics> list =	shopStatisticsMapper.selectShopToDay(shopStatisticsSqlVO);
    	if(list!=null && list.size()>0) {
    		shopStatistics = list.get(0);
    		QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
			queryWrapper.between("spread_time", strTime, endTime);
			queryWrapper.eq("dept_dp_id", deptDpId);
			if(spreaduid!=null) {
				queryWrapper.eq("spreaduid", spreaduid);
			}
			shopStatistics.setMemberDayConut(memberMapper.selectCount(queryWrapper));
    		return shopStatistics;
    	}
        return null;
    }
    
    
    /**
     * 批量删除直播间数据统计
     *
     * @param ids 需要删除的店铺数据统计主键
     * @return 结果
     */
    public  ShopStatistics selectShopToDayByDeptZbjId(Long deptZbjId,String date) {
    	ShopStatistics shopStatistics = null;
//        LocalDate thisDate = LocalDate.now();
//    	LocalDateTime strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
//  	 	LocalDateTime endTime  = LocalDateTime.of(thisDate, LocalTime.MAX);
//  	 	
  	 	LocalDate thisDate = LocalDate.now();
    	if(date!=null) {
    		thisDate = LocalDate.parse(date);
    	}
        LocalDateTime strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
    	LocalDateTime endTime = LocalDateTime.of(thisDate, LocalTime.MAX);
    	
       	int tjdata = Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd"));
 		int	tjyear = Integer.parseInt(DateUtil.format(strTime, "yyyy"));
 		int	tjmonth = Integer.parseInt(DateUtil.format(strTime, "MM"));
 		int	tjweek = Integer.parseInt(DateUtil.format(strTime, "w"));
 		int	tjday = Integer.parseInt(DateUtil.format(strTime, "dd"));
 		ShopStatisticsSqlVO shopStatisticsSqlVO = new ShopStatisticsSqlVO();
    	shopStatisticsSqlVO.setCreateTime(LocalDateTime.now());
    	shopStatisticsSqlVO.setStrTime(strTime);
    	shopStatisticsSqlVO.setEndTime(endTime);
    	shopStatisticsSqlVO.setTjdata(tjdata);
    	shopStatisticsSqlVO.setTjyear(tjyear);
    	shopStatisticsSqlVO.setTjmonth(tjmonth);
    	shopStatisticsSqlVO.setTjweek(tjweek);
    	shopStatisticsSqlVO.setTjday(tjday);
    	shopStatisticsSqlVO.setDeptZbjId(deptZbjId);
    	shopStatisticsSqlVO.setGroupByType(1);
    	shopStatisticsSqlVO.setGroupBy("dept_zbj_id");
    	shopStatisticsSqlVO.setGroupByzd("dept_zbj_id,");
    	if(deptZbjId == null) {
        	shopStatisticsSqlVO.setGroupByType(0);
        	shopStatisticsSqlVO.setGroupBy(null);
        	shopStatisticsSqlVO.setGroupByzd(null);
    	}
    	List<ShopStatistics> list =	shopStatisticsMapper.selectShopToDay(shopStatisticsSqlVO);
    	if(list!=null && list.size()>0) {
    		shopStatistics = list.get(0);
    		return shopStatistics;
    	}
        return null;
    }
    
    
}
